package com.heima.article.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitConfig implements InitializingBean {

    @Autowired
    RabbitTemplate  rabbitTemplate;
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("初始化mq");
        //设置消息转换器
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //设置发送确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (!b){
                    log.info("消息发送失败");
                }
            }
        });
        //设置消息返回
        // 设置消息返还 回调方法
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                // TODO 可扩展自动重试
                log.error("消息返还回调触发  ，交换机: {} , 路由: {} , 消息内容: {} , 原因: {}  ",s1,s2,message,i);
            }
        });
    }
}
